package com.ruoyi.project.channel.channelCode.service;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.Md5Utils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.channel.channelAccount.domain.ChannelAccount;
import com.ruoyi.project.channel.channelAccount.service.IChannelAccountService;
import com.ruoyi.project.pay.PayServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.channel.channelCode.mapper.ChannelCodeMapper;
import com.ruoyi.project.channel.channelCode.domain.ChannelCode;
import com.ruoyi.project.channel.channelCode.service.IChannelCodeService;
import com.ruoyi.common.utils.text.Convert;

/**
 * 钉钉产码 服务层实现
 *
 * @author CAIN
 * @date 2019-06-21
 */
@Service
public class ChannelCodeServiceImpl implements IChannelCodeService {
    @Autowired
    private ChannelCodeMapper channelCodeMapper;
    @Autowired
    private IChannelAccountService channelAccountService;
    private static final Logger log = LoggerFactory.getLogger(PayServiceImpl.class);
    /**
     * 查询钉钉产码信息
     *
     * @param ddId 钉钉产码ID
     * @return 钉钉产码信息
     */
    @Override
    public ChannelCode selectChannelCodeById(Long ddId) {
        return channelCodeMapper.selectChannelCodeById(ddId);
    }

    /**
     * 查询钉钉产码列表
     *
     * @param channelCode 钉钉产码信息
     * @return 钉钉产码集合
     */
    @Override
    public List<ChannelCode> selectChannelCodeList(ChannelCode channelCode) {
        return channelCodeMapper.selectChannelCodeList(channelCode);
    }

    /**
     * 新增钉钉产码
     *
     * @param channelCode 钉钉产码信息
     * @return 结果
     */
    @Override
    public int insertChannelCode(ChannelCode channelCode) {
        return channelCodeMapper.insertChannelCode(channelCode);
    }

    @Override
    public AjaxResult insertChannelCode(String mark, String money, String msg, String sign) {
        //TODO: 鉴权
        try {
            String str = URLDecoder.decode(msg, "utf-8");
            JSONObject jsonObject = JSONObject.parseObject(str);
            ChannelCode channelCode = new ChannelCode();
            channelCode.setMark(mark);
            channelCode.setDdMethod(jsonObject.getString("method"));
            channelCode.setAmount(BigDecimal.valueOf(Double.valueOf(money)));
            channelCode.setBizId(jsonObject.getString("bizId"));
            channelCode.setMasterId(jsonObject.getString("creator"));
            channelCode.setCmd(jsonObject.getString("cmd"));
            channelCode.setSlaveId(jsonObject.getString("id"));
            channelCode.setDdStatus("0");
            channelCode.setGroupBillName(jsonObject.getString("groupBillName"));
            JSONObject qrcode = jsonObject.getJSONObject("qrcode");
            channelCode.setPayUrl(qrcode.getString("payUrl"));
            ChannelAccount searchAccount = new ChannelAccount();
            searchAccount.setAppid(channelCode.getMasterId());
            searchAccount.setPayType("08");
            List<ChannelAccount> accounts = channelAccountService.selectChannelAccountList(searchAccount);
            if(accounts.size() == 0){
                log.error("钉钉号账号系统未注册："+channelCode.toString());
                return  AjaxResult.error("钉钉号账号系统未注册");
            }
            channelCode.setChannelId(accounts.get(0).getChannelUserId());
            channelCode.setCreateTime(new Date());
            channelCode.setAccount(accounts.get(0).getAccount());
            // 查看系统是否有这个单号，如果有则不入库
            ChannelCode searchCode = new ChannelCode();
            searchCode.setMasterId(channelCode.getMasterId());
            searchCode.setBizId(channelCode.getBizId());
            searchCode.setSlaveId(channelCode.getSlaveId());
            searchCode.setAmount(channelCode.getAmount());
            List<ChannelCode> codes= selectChannelCodeList(searchCode);
            if(codes.size()>0){
                // 已经存在这种账号了 不需要再入库
                log.error("系统已经存在这种码了 不需要再入库:"+channelCode);
                return AjaxResult.error("系统已经存在这种码了 不需要再入库:"+channelCode);
            }
            insertChannelCode(channelCode);
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(),e);
            return  AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success("成功");
    }

    @Override
    public AjaxResult insertChannelCodes(String no, String qrList,String dt, String sign) {
        //TODO:
            String _sign = Md5Utils.androidMD5(dt+no+"cainiao666888999");
//            if(!_sign.equals(sign)){
//                log.info("旺信鉴权失败");
//                return AjaxResult.error("失败");
//            }
//            String str = URLDecoder.decode(msg, "utf-8");
            JSONArray jsonArray = JSONObject.parseArray(qrList);
            for(int i=0;i<jsonArray.size();i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String money = jsonObject.getString("money");
                String orderNo = jsonObject.getString("orderNo");
                String payUrl = jsonObject.getString("payUrl");
                String qunId = jsonObject.getString("qunId");
                ChannelCode channelCode = new ChannelCode();
                channelCode.setAmount(BigDecimal.valueOf(Double.valueOf(money)));
                channelCode.setPayUrl(payUrl);
                channelCode.setMasterId(qunId);
                channelCode.setDdStatus("0");
                channelCode.setBizId(orderNo);
                ChannelAccount searchAccount = new ChannelAccount();
                searchAccount.setAccount(no);
                searchAccount.setPayType("28");
                List<ChannelAccount> accounts = channelAccountService.selectChannelAccountList(searchAccount);
                if(accounts.size() == 0){
                    log.error("旺信账号系统未注册："+channelCode.toString());
                    return  AjaxResult.error("旺信账号系统未注册");
                }
                channelCode.setChannelId(accounts.get(0).getChannelUserId());
                channelCode.setCreateTime(new Date());
                channelCode.setAccount(accounts.get(0).getAccount());
                // 查看系统是否有这个单号，如果有则不入库
                ChannelCode searchCode = new ChannelCode();
                searchCode.setPayUrl(payUrl);
                List<ChannelCode> codes= selectChannelCodeList(searchCode);
                if(codes.size()>0){
                    // 已经存在这种账号了 不需要再入库
                    log.error("系统已经存在这种码了 不需要再入库:"+channelCode);
                    continue;
                }
                insertChannelCode(channelCode);
            }
        return AjaxResult.success("成功");
    }

    /**
     * 修改钉钉产码
     *
     * @param channelCode 钉钉产码信息
     * @return 结果
     */
    @Override
    public int updateChannelCode(ChannelCode channelCode) {
        return channelCodeMapper.updateChannelCode(channelCode);
    }

    /**
     * 删除钉钉产码对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteChannelCodeByIds(String ids) {
        return channelCodeMapper.deleteChannelCodeByIds(Convert.toStrArray(ids));
    }

}
